import { useState, useEffect } from "react";
import { friendLinkColumn } from "./column";
import { Input, Button, Table, Modal, Form, Radio } from "antd";
import { SearchOutlined, RedoOutlined, PlusOutlined } from "@ant-design/icons";
import friendlinkStyle from "./dict.module.scss";
import { queryFriendLinks, modifyFriendLinkById,addFriendLink } from "@/api/index.js";
import Blupload from "@/components/Blupload";
export default function FriendLink() {
  const [paginationObj, setPaginationObj] = useState({ page: 1, size: 10 });
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState([]);
  const [name, setName] = useState("");
  const [editVisible, setEditVisible] = useState(false);
  const [addVisible, setAddVisible] = useState(false);
  const [titleImg, setTitleImg] = useState("");
  const [addTitleImg, setAddTitleImg] = useState("");
  const [modifyId, setModifyId] = useState(-1);
  const requireRule = { required: true, message: "必填字段" };
  const [form] = Form.useForm();
  const [addform] = Form.useForm();
  useEffect(() => {
    getList();
  }, []);

  const getList = async (requestObj = {}) => {
    setLoading(true);
    const res = await queryFriendLinks(requestObj);
    console.log("links", res);
    setList(res.data);
    setLoading(false);
  };

  const handleName = (e) => {
    setName(e.target.value);
  };

  const handleSearch = () => {
    let requestObj = {};
    if (name) {
      requestObj.name = name;
    }
    getList(requestObj);
    handleResetSearch();
  };

  const handleResetSearch = () => {
    setName("");
  };

  const handlePageChange = (page, size) => {
    // getList({ page, size });
  };

  const handleSizeChange = (page, size) => {
    // getList({ page, size });
  };

  // 编辑
  const handleOpenEditVisible = (row) => {
    setModifyId(row.id);
    console.log(row, "数据");
    const { icon, name, description, ip_address } = row;
    form.setFieldsValue({
      name,
      description,
      ip_address,
    });
    setTitleImg(icon);
    setEditVisible(true);
  };

  // 点击switch
  const handleSwitchStatus = async (row) => {
    const { id, status } = row;
    let requestObj = { id };
    if (status === 1) {
      requestObj.status = 0;
    } else {
      requestObj.status = 1;
    }
    console.log(requestObj, "switch");
    const res = await modifyFriendLinkById(requestObj);
    if (res && res.code == 200) {
      window.$message.success("修改成功！");
    }
    getList();
  };

  const handleCloseEditVisible = () => {
    setEditVisible(false);
    form.resetFields();
    setModifyId(-1);
  };

  const handleFinish = async (value) => {
    const requestObj = value;
    requestObj.icon = titleImg;
    requestObj.id = modifyId;
    // console.log(requestObj, "value");
    const res = await modifyFriendLinkById(requestObj);
    if (res && res.code == 200) {
      window.$message.success("修改成功！");
    }
    handleCloseEditVisible();
    getList();
  };

  const handleFinishFail = () => {};

  // 自定义处理上传

  const handleUploadChange = (titleImg) => {
    if (titleImg != "delete") {
      console.log(titleImg, "title");
      setTitleImg(titleImg);
    } else {
      setTitleImg("");
    }
  };
  const handleAddUploadChange = (titleImg) => {
    if (titleImg != "delete") {
      console.log(titleImg, "title");
      setAddTitleImg(titleImg);
    } else {
      setAddTitleImg("");
    }
  };
  const columns = friendLinkColumn({
    handleOpenEditVisible,
    handleSwitchStatus,
  });
  // 新增
  const handleCloseAddVisible = () => {
    setAddVisible(false);
    addform.resetFields();
    setAddTitleImg("");
  };
  const handleOpenAddVisible = () => {
    setAddVisible(true);
  };

  const handleAddFinishFail = () => {};

  const handleAddFinish = async(value) => {
    const requestObj = value;
    requestObj.icon = addTitleImg;
    console.log(requestObj, "value");
    const res = await addFriendLink(requestObj);
    if (res && res.code == 200) {
      window.$message.success("添加成功！");
    }
    handleCloseAddVisible();
    getList();
  };
  return (
    <div className={friendlinkStyle.dict}>
      <div className={friendlinkStyle.top}>
        <div className={friendlinkStyle.search}>
          <h3>友链名称:</h3>
          <Input
            placeholder="请输入友链名称"
            value={name}
            onChange={handleName}
            style={{ width: "200px", marginRight: "10px" }}
          />
          <Button
            icon={<SearchOutlined />}
            type="primary"
            className={friendlinkStyle["ant-btn"]}
            onClick={handleSearch}
          >
            查找
          </Button>
          <Button
            icon={<RedoOutlined />}
            className={friendlinkStyle["ant-btn"]}
            onClick={handleResetSearch}
          >
            重置
          </Button>
        </div>
        <Button
          icon={<PlusOutlined />}
          type="primary"
          onClick={handleOpenAddVisible}
        >
          新增
        </Button>
      </div>
      <div className={friendlinkStyle["table-container"]}>
        <Table
          bordered
          sticky
          columns={columns}
          dataSource={list}
          rowKey={(record) => record.id}
          loading={loading}
          pagination={{
            pageSize: paginationObj.pageSize,
            current: paginationObj.currentPage,
            pageSizeOptions: [3, 5, 10, 20],
            showSizeChanger: true,
            total: paginationObj.total,
            showTotal: (total) => `共${total}条`,
            onChange: handlePageChange,
            onShowSizeChange: handleSizeChange,
          }}
        />
      </div>
      {/* 编辑 */}
      <Modal
        open={editVisible}
        onCancel={handleCloseEditVisible}
        title="编辑友情链接"
        footer={false}
      >
        <Form
          style={{ padding: "20px" }}
          form={form}
          onFinishFailed={handleFinishFail}
          onFinish={handleFinish}
        >
          <Form.Item label="头像">
            <Blupload
              handleUploadChange={handleUploadChange}
              titleImg={titleImg}
            />
          </Form.Item>
          <Form.Item label="网站名称" name="name" rules={[requireRule]}>
            <Input></Input>
          </Form.Item>
          <Form.Item label="网站描述" name="description" rules={[requireRule]}>
            <Input></Input>
          </Form.Item>
          <Form.Item label="网站地址" name="ip_address" rules={[requireRule]}>
            <Input></Input>
          </Form.Item>

          <Form.Item style={{ textAlign: "center" }}>
            <Button
              onClick={handleCloseEditVisible}
              style={{ marginRight: "40px" }}
            >
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      {/* 新增 */}
      <Modal open={addVisible} onCancel={handleCloseAddVisible} footer={null}>
        <Form
          style={{ padding: "20px" }}
          form={addform}
          onFinishFailed={handleAddFinishFail}
          onFinish={handleAddFinish}
        >
          <Form.Item label="头像">
            <Blupload
              handleUploadChange={handleAddUploadChange}
              titleImg={addTitleImg}
            />
          </Form.Item>
          <Form.Item label="网站名称" name="name" rules={[requireRule]}>
            <Input></Input>
          </Form.Item>
          <Form.Item label="网站描述" name="description" rules={[requireRule]}>
            <Input></Input>
          </Form.Item>
          <Form.Item label="网站地址" name="ip_address" rules={[requireRule]}>
            <Input></Input>
          </Form.Item>

          <Form.Item style={{ textAlign: "center" }}>
            <Button
              onClick={handleCloseAddVisible}
              style={{ marginRight: "40px" }}
            >
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
